package com.dede.mypermission

import android.app.Fragment
import android.content.pm.PackageManager
import android.support.v4.content.ContextCompat

/**
 * @author hsh
 * @date 2017/8/23 14:15.
 * @doc
 */
class PermissionRequestImpl(private val fragment: Fragment) : PermissionRequest {

    override fun request() {
        if (permissions.isEmpty()) return

        val requestPermissions = arrayListOf<String>()
        permissions.filter {
            val result = checkedPermission(it)
            if (result) {
                val permission = Permission()
                permission.permission = it
                permission.requestCode = requestCode
                permission.isGrantResult = result
                permission.isShouldShowRequestPermissionRationale = fragment.shouldShowRequestPermissionRationale(it)
                granted(permission)
            }
            result.not()
        }.forEach { requestPermissions.add(it) }

        if (requestPermissions.isEmpty()) return

        fragment.requestPermissions(requestPermissions.toArray(arrayOfNulls(requestPermissions.size)), requestCode)
    }

    override fun checkRequest() {
        if (permissions.isEmpty()) return

        val requestPermissions = arrayListOf<String>()
        permissions.filter { checkedPermission(it).not() }
                .forEach { requestPermissions.add(it) }

        if (requestPermissions.isEmpty()) return
        fragment.requestPermissions(requestPermissions.toArray(arrayOfNulls(requestPermissions.size)), requestCode)
    }

    private var permissions = arrayListOf<String>()

    override fun permission(vararg permissions: String): PermissionRequest {
        this.permissions = permissions.toCollection(arrayListOf())
        return this
    }

    var requestCode = 66

    override fun requestCode(requestCode: Int): PermissionRequest {
        this.requestCode = requestCode
        return this
    }

    var granted: ((permission: Permission) -> Unit) = {}
    var denied: ((permission: Permission) -> Unit) = {}

    override fun onGranted(granted: (permission: Permission) -> Unit): PermissionRequest {
        this.granted = granted
        return this
    }

    override fun onDenied(denied: (permission: Permission) -> Unit): PermissionRequest {
        this.denied = denied
        return this
    }

    override fun request(vararg permissions: String) {
        this.permissions = permissions.toCollection(arrayListOf())
        request()
    }

    override fun checkRequest(vararg permissions: String) {
        this.permissions = permissions.toCollection(arrayListOf())
        checkRequest()
    }

    override fun checkedPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(fragment.context, permission) == PackageManager.PERMISSION_GRANTED
    }
}